import { showMessage } from '@/components/antd-comp/message'
import { create } from 'zustand'

type funcsState = {
  needFuncAuth: boolean
  funcCodes: string[]
}

type Actions = {
  setNeedFuncAuth: (status: boolean) => void
  setFuncCodes: (codes: string[]) => Promise<any>
  /**
   * 存在一个有效code码即可访问对应服务
   */
  hasFuncPermission: (codes: string[], prompt?: boolean) => boolean
}

/**
 * 用户权限列表，使用migu跳转登录时设置needAuth为true，启用Permission校验，本地登录暂不校验权限
 */
export const useFuncsStore = create<funcsState & Actions>(set => ({
  needFuncAuth: false,
  funcCodes: [],
  setNeedFuncAuth: status => {
    set({ needFuncAuth: status })
  },
  setFuncCodes: codes => {
    set({ funcCodes: [...codes] })
    return Promise.resolve()
  },
  hasFuncPermission: (codes: string[], prompt = true) => {
    console.log(`>>>检查【${codes}】权限`)
    const currentState = useFuncsStore.getState()
    if (!currentState.needFuncAuth) {
      return true
    }

    for (let i = 0; i < codes.length; i++) {
      if (currentState.funcCodes.includes(codes[i])) {
        return true
      }
    }
    if (prompt) {
      showMessage({
        content: '暂无该功能权限，请联系企业超级管理员',
        type: 'warning'
      })
    }
    return false
  }
}))
